<?php 
namespace common\bot;

use common\libs\Curl;
use common\model\sell66\Bot;
use common\service\QueueService;
class SteamBotService{
	
	public static $instance = null;

    public $pickNum = 0;

    function __construct($bot = null) {
        set_time_limit(0);

    }

	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}

    /**
     * 解析交易页面，获取对方escrow天数
     */
    public function getPartnerTradeEscrow($steam,$tradeUrl) {
    	return array("code"=>true);
        $response = $steam->cURL($tradeUrl);
        if (preg_match('/var\sg_daysMyEscrow\s=\s(\d+);\s+var\sg_daysTheirEscrow\s=\s(\d+);/', $response, $matches)) {
        	if($matches[2]>0){
        		return array("code"=>false,'message'=>'您需要启用Steam令牌手机认证器至少7天');
//                 throw new \Exception('您需要启用Steam令牌手机认证器至少7天', 1);
            }else{
                return array("code"=>true);
            }
        } else {
            if($response && strpos($response, '<div id="error_page_bg">') !== false) {
            	return array("code"=>false,'message'=>'交易链接无效或库存未公开');
//                 throw new \Exception('交易链接无效或库存未公开', 1);
            }else{
            	return array("code"=>false,'message'=>'steam交易链接加载失败,请刷新尝试');
//                 throw new \Exception('交易链接加载失败');
            }
        }
    }

    public function rpcCheckTradeUrl($tradeUrl, $steamId)
    {
        $url = getenv('rpc_trade_url');
        $url = $url . '/LAN/checkTradeurl';

        $param = array(
            'tradeUrl'=>$tradeUrl,
            'steamId'=>$steamId,
        );

        $res = Curl::http_post($url, $param);
        $res = json_decode($res, true);

        if($res['code'] == 1){
            return ['code'=> true, 'botInfo' => $res['result']];
        }else{
            return ['code'=>false, 'message'=> isset($res['msg']) ? $res['msg'] : '交易链接无效或库存未公开'];
        }
    }

    public function rpcSentTrade($appId, $steamId, $tradeUrl, $oids, $sourceType = 'skinbank')
    {
        $url = getenv('rpc_trade_url');
        $url = $url . '/trade/create';

        $param = array(
            'app_id' => $appId,
            'steam_id' => $steamId,
            'tradeUrl' => $tradeUrl,
            'o_ids' => $oids,
            'source_type' => $sourceType,
        );

        $res = Curl::http_post_for_send_trade($url, $param);
        $res = json_decode($res, true);

        if($res['code'] == 1){
            return ['code'=> true, 'data' => $res['result']];
        }else{
            return ['code'=>false, 'message'=> isset($res['msg']) ? $res['msg'] : '报价发送失败'];
        }
    }

    public function rpcCheckFrom($fromTradeId)
    {
        $url = getenv('rpc_trade_url');

        $param = array(
            'from_trade_id'=>$fromTradeId,
        );

        $url = $url . '/check/from?'.http_build_query($param);

        $res = Curl::http_get($url, $param);
        $res = json_decode($res, true);

        if($res['code'] == 1){
            return ['code'=> true, 'data' => $res['result']];
        }else{
            return ['code'=>false, 'message'=> isset($res['msg']) ? $res['msg'] : '-4'];
        }
    }

    public function rpcSendOutTrade($steamId, $tradeUrl, array $list, $sourceType = 'skinbank')
    {
        $url = getenv('rpc_trade_url');
        $url = $url . '/trade/out';

        $param = array(
            'steam_id' => $steamId,
            'tradeUrl' => $tradeUrl,
            'list' => json_encode($list),
            'source_type' => $sourceType,
        );

        $res = Curl::http_post($url, $param);
        $res = json_decode($res, true);

        if($res['code'] == 1){
            return ['code'=> true, 'data' => $res['result']];
        }else{
            return ['code'=>false, 'message'=> isset($res['msg']) ? $res['msg'] : '报价发送失败'];
        }
    }

    public function rpcCheckOut($tradeofferoutId)
    {
        $url = getenv('rpc_trade_url');

        $param = array(
            'outTradeId' => $tradeofferoutId,
        );

        $url = $url . '/check/out?'.http_build_query($param);

        $res = Curl::http_get($url, $param);
        $res = json_decode($res, true);

        if($res['code'] == 1){
            return ['code'=> true, 'data' => $res['result']];
        }else{
            return ['code'=>false, 'message'=> isset($res['msg']) ? $res['msg'] : '-4'];
        }
    }


    /**
     * 检测交易链接是否失效
     * @param $tradeUrl
     * @return array
     */
    public function checkTradeUrl($tradeUrl)
    {
        if (empty($tradeUrl)) {
            return array("code" => false, 'message' => '交易链接未填写');
        }

        $bot = Bot::getCheckTradeUrlLivingBot();
        if (empty($bot)) {
            return array("code" => false, 'message' => '系统繁忙，请稍后再试');
        }

        $steam = $bot['steam'];
        if (empty($steam)) {
            if($this->pickNum < 3){
                $this->pickNum ++;
                QueueService::getInstance()->setAdapter('login_bot')->loginBot($bot['id'], $bot['client_no']);
                return $this->checkTradeUrl($tradeUrl);
            }else{
                return array("code" => false, 'message' => '系统繁忙，请稍后再试');
            }
        }
        $response = $steam->cURL($tradeUrl);
        if (preg_match('/var\sg_daysMyEscrow\s=\s(\d+);\s+var\sg_daysTheirEscrow\s=\s(\d+);/', $response, $matches)) {
            if ($matches[2] > 0) {
                return array("code" => false, 'message' => '您需要启用Steam令牌手机认证器至少7天');
            } else {
                return array("code" => true, 'botInfo'=>['bot_id'=>$bot['id']]);
            }
        } else {
            if ($response && strpos($response, '<div id="error_page_bg">') !== false) {
                return array("code" => false, 'message' => '交易链接无效或库存未公开');
            } else {
                return array("code" => false, 'message' => 'steam交易链接加载失败,请过5分钟再尝试');
            }
        }
    }
}